from infra.handler import BaseHandler
# from common.log import logInfo
from .activity_db import create_new_activity
from .activity_db import update_activity_info
from .activity_db import get_activity_info
from .activity_db import get_activity_list
from .activity_db import get_nearby_activities
from domain.chatroom.chatroom_db import create_chatroom
from domain.chatroom.chatroom_db import delete_chatroom
from domain.chatroom.chatroom_db import get_chatroom_by_activity
from domain.activity.activity_db import get_activity_type_fav_stats
from domain.reg.reg_db import get_user_regs
from domain.message.message_db import insert_message
import json

class ActivityHandler(BaseHandler):
    async def get(self):
        """获取活动信息"""
        try:
            current_user, _ = self.get_current_user()
            if not current_user:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return

            # 获取查询参数
            user_id = self.get_argument('user_id', None)
            activity_id = self.get_argument('activity_id', None)
            activity_type = self.get_argument('type', None)  # want_to_go, registered, created, finished
            latitude = self.get_argument('latitude', None)  # 添加纬度参数
            longitude = self.get_argument('longitude', None)  # 添加经度参数
            distance = self.get_argument('distance', 10)  # 添加距离参数
            city = self.get_argument('city', None)
            keyword = self.get_argument('keyword', None)
            # 添加日期区间参数
            start_date = self.get_argument('start_date', None)
            end_date = self.get_argument('end_date', None)

            # 添加新的筛选参数
            filter_type = self.get_argument('type', None)  # 活动类型筛选
            area = self.get_argument('area', None)  # 地区筛选
            people = self.get_argument('people', None)  # 人数筛选

            if activity_id:
                # 查询单个活动详情
                success, result = await get_activity_info(int(activity_id), current_user)
            else:
                # 查询活动列表
                status = self.get_argument('status', None)
                status_list = [int(s) for s in status.split(',')] if status else None
                page = int(self.get_argument('page', 1))
                page_size = int(self.get_argument('page_size', 20))
                 # 如果提供了经纬度，查询附近的活动
                if latitude and longitude:
                    success, result = await get_nearby_activities(
                        latitude=float(latitude),
                        longitude=float(longitude),
                        distance=float(distance),  # 10公里范围内
                        activity_type=activity_type,
                        status=status_list,
                        page=page,
                        page_size=page_size
                    )
                else:
                   # 查询所有活动，添加筛选参数
                    success, result = await get_activity_list(
                        user_id=user_id,
                        activity_type=filter_type,  # 使用筛选类型
                        status=status_list,
                        page=page,
                        page_size=page_size,
                        start_date=start_date,
                        end_date=end_date,
                        city=city,
                        keyword=keyword,
                        area=area,  # 添加地区筛选
                        people=people  # 添加人数筛选
                    )

            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "查询成功",
                    "data": result
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": f"查询失败: {result}"
                }))

        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))

    async def post(self):
        """创建新活动"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            body = json.loads(self.request.body.decode('utf-8'))
            # 检查必填字段
            required_fields = [
                "name", "content", "type", "address", "address_name",
                "longitude", "latitude", "images", "people_number",
                "fee", "start_time", "end_time"
            ]
            
            for field in required_fields:
                if field not in body:
                    self.write(json.dumps({
                        "code": 400,
                        "msg": f"缺少必填字段: {field}"
                    }))
                    return
            success, result = await create_new_activity(user_id, body)
            
            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "活动创建成功",
                    "data": {"activity_id": result}
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": f"创建活动失败: {result}"
                }))

        except json.JSONDecodeError:
            self.write(json.dumps({
                "code": 404,
                "msg": "请求体格式错误"
            }))
        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))
    
    async def put(self):
        """修改活动信息"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            body = json.loads(self.request.body)
            # activity_id = self.get_argument('activity_id', None)
            if 'activity_id' not in body:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "缺少活动ID"
                }))
                return      
            # 检查可修改字段
            allowed_fields = [
                "name", "content", "type", "people_number",
                "people_age", "fee", "start_time", "end_time",
                "images", "status", "address", "address_name", "longitude", "latitude"
            ]
            update_data = {k: v for k, v in body.items() if k in allowed_fields}
            if not update_data:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "没有可更新的字段"
                }))
                return
            success, result = await update_activity_info(
                activity_id= body['activity_id'],
                user_id=user_id,
                activity_data=update_data
            )
            
            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "活动更新成功"
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": f"更新失败: {result}"
                }))

        except json.JSONDecodeError:
            self.write(json.dumps({
                "code": 400,
                "msg": "请求体格式错误"
            }))
        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))

class ActivityStartHandler(BaseHandler):
    async def post(self):
        """开始活动"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return

            body = json.loads(self.request.body)
            if 'activity_id' not in body:
                self.write(json.dumps({"code": 400, "msg": "缺少活动ID"}))
                return

            # 检查是否是活动创建者
            activity_info = await get_activity_info(body['activity_id'], user_id)
           
            if not activity_info[0] or activity_info[1]['created_user_id'] != user_id:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "只有活动创建者可以开始活动"
                }))
                return
            # 获取报名人名单
            current_members = activity_info[1]['joiners_ids']
            current_members.append(str(user_id))
            # 创建群聊
            chat_success, chat_result = await create_chatroom(
                activity_id=body['activity_id'],
                creator_id=user_id,
                member_list=current_members,
                group_name=activity_info[1]['name'],  # 使用活动名称作为群名
                notification=f"活动时间：{activity_info[1]['start_time']} - {activity_info[1]['end_time']}\n活动地点：{activity_info[1]['address']['name']}"
            )

            if not chat_success:
                self.write(json.dumps({
                    "code": 400,
                    "msg": f"创建群聊失败: {chat_result}"
                }))
                return

            # 更新活动状态为进行中
            success, result = await update_activity_info(body['activity_id'], user_id, {'status': 1})
            # print("chat_result",result)
            if success:
                  # 给所有参与者发送活动开始通知
                for member_id in current_members:
                    await insert_message(
                        type="activity",
                        title="活动开始通知",
                        content=f"活动 {activity_info[1]['name']} 已开始，群聊已创建，请查看群聊了解详情。\n活动时间：{activity_info[1]['start_time']} - {activity_info[1]['end_time']}\n活动地点：{activity_info[1]['address']['name']}",
                        receiver_id=int(member_id),
                        sender_id=user_id,
                        activity_id=body['activity_id']
                    )
                self.write(json.dumps({
                    "code": 200,
                    "msg": "活动已开始",
                    "data": {
                        "group_id": chat_result,
                        "member_count": len(current_members)
                    }
                }))
            else:
                self.write(json.dumps({
                    "code": 400,
                    "msg": f"更新活动状态失败: {result}"
                }))

        except Exception as e:
            self.write(json.dumps({
                "code": 400,
                "msg": str(e)
            }))

class ActivityCancelHandler(BaseHandler):
    async def post(self):
        """取消活动"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return

            body = json.loads(self.request.body)
            if 'activity_id' not in body:
                self.write(json.dumps({"code": 400, "msg": "缺少活动ID"}))
                return

            # 检查是否是活动创建者
            activity_info = await get_activity_info(body['activity_id'], user_id)
            if not activity_info[0] or activity_info[1]['created_user_id'] != user_id:
                self.write(json.dumps({
                    "code": 403,
                    "msg": "只有活动创建者可以取消活动"
                }))
                return

            # 检查活动状态
            if activity_info[1]['status'] == 2:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "活动已结束，无法取消"
                }))
                return

            # 更新活动状态为已取消
            success, result = await update_activity_info(
                activity_id=body['activity_id'],
                user_id=user_id,
                activity_data={'status': 3}  # 3表示已取消
            )

            if success:
                # 给创建者发送活动取消通知
                await insert_message(
                    type="activity",
                    title="活动取消通知",
                    content=f"您已成功取消活动 {activity_info[1]['name']}",
                    receiver_id=user_id,
                    sender_id=user_id,
                    activity_id=body['activity_id']
                )
                # 给所有报名用户发送活动取消通知
                for joiner_id in activity_info[1]["joiners_ids"]:
                    await insert_message(
                        type="activity",
                        title="活动取消通知",
                        content=f"您报名的活动 {activity_info[1]['name']} 已被创建者取消",
                        receiver_id=joiner_id,
                        sender_id=user_id,
                        activity_id=body['activity_id']
                    )
                # 获取聊天室信息
                chat_info = await get_chatroom_by_activity(body['activity_id'])
                if chat_info[0]:
                    # 删除群聊
                    chat_success, chat_result = await delete_chatroom(chat_info[1]['id'])
                    if not chat_success:
                        self.write(json.dumps({
                            "code": 400,
                            "msg": f"取消活动成功，但删除群聊失败: {chat_result}"
                        }))
                        return

                self.write(json.dumps({
                    "code": 200,
                    "msg": "活动已取消"
                }))
            else:
                self.write(json.dumps({
                    "code": 400,
                    "msg": f"取消活动失败: {result}"
                }))

        except Exception as e:
            self.write(json.dumps({
                "code": 400,
                "msg": str(e)
            }))

class ActivityTypeFavListHandler(BaseHandler):
    async def get(self):
        """获取活动类型收藏列表"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return

            # 获取查询参数
            city = self.get_argument('city', None)  # 可选的城市参数
            
            # 获取收藏统计数据
            success, result = await get_activity_type_fav_stats(city)
            
            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "获取成功",
                    "data": result
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": f"获取失败: {result}"
                }))

        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))

class ActivityFinishListHandler(BaseHandler):
    async def get(self):
        """获取用户的所有相关活动（已报名和已发起）"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            # 获取筛选参数
            activity_type = self.get_argument('type', None)
            area = self.get_argument('area', None)
            people = self.get_argument('people', None)
            page = int(self.get_argument('page', 1))
            page_size = int(self.get_argument('page_size', 100))

            # 获取用户已报名的活动
            _, reg_result = await get_user_regs(
                user_id, page, page_size, 
                activity_type=activity_type, 
                area=area, 
                people=people
            )
            finished_registered = [activity for activity in reg_result["list"] 
                                if activity["status"] in [2, 3]]  # 2表示已结束，3表示已取消

            # 获取用户已发起的所有活动（带筛选条件）
            success, result = await get_activity_list(
                user_id=user_id,
                activity_type=activity_type,
                area=area,
                people=people,
                status=[2, 3],  # 2表示已结束，3表示已取消
                page=page,
                page_size=page_size
            )

            if success:
                # 合并已报名和已发起的活动列表
                all_activities = finished_registered + result["activities"]
                self.write(json.dumps({
                    "code": 200,
                    "msg": "获取成功",
                    "data": all_activities
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": f"获取失败: {result}"
                }))

        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))